//
//  ViewController.m
//  AWS Viewer
//
//  Created by Vincent de Smet on 9/16/13.
//  Copyright (c) 2013 TI Avans. All rights reserved.
//

#import "TableViewController.h"
#import "AFHTTPClient.h"
#import "AFHTTPRequestOperation.h"
#import "CurrentAwsData.h"
#import "AdvancedTableCell.h"
#import "GraphViewController.h"
#import "ImageCell.h"

@interface TableViewController ()

@end

@implementation TableViewController
@synthesize currentAwsData;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    // Fill array data
    [self UpdateData];
    tableData = [NSArray arrayWithObjects:@"Air Pressure" , @"Humidity", @"Rain Rate", @"Temperature" , @"Wind Direction", @"Wind Speed", nil];
    
    UIRefreshControl *refreshController = [[UIRefreshControl alloc]
                                        init];
    [refreshController addTarget:self action:@selector(UpdateData) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refreshController;
    
    double framerate = 60.0f/1.0f;
    [NSTimer scheduledTimerWithTimeInterval:framerate
                                     target:self
                                   selector:@selector(UpdateData)
                                   userInfo:nil
                                    repeats:YES];
}

-(void)UpdateData
{
    //Fetch AWS Data
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://xively.com/"]];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                            path:@"https://api.xively.com/v2/feeds/40053.json"
                                                      parameters:nil];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
    // Set API Key Header
    [request setValue:XIVELY_API_KEY forHTTPHeaderField:@"X-ApiKey"];
    
    
    // Request data
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self operationCompleted:operation byResponse:responseObject];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self operationFailed:operation withError:error];
    }];
    [operation start];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tableData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"AdvancedTableCell";
    static NSString *imageTableIdentifier = @"ImageCell";

    AdvancedTableCell *cell = (AdvancedTableCell *) [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    ImageCell *imageCell = (ImageCell *) [tableView dequeueReusableCellWithIdentifier:imageTableIdentifier];
    
    if (cell == nil) 
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:simpleTableIdentifier owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    if (imageCell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:imageTableIdentifier owner:self options:nil];
        imageCell = [nib objectAtIndex:0];
    }
    cell.Title.text = [tableData objectAtIndex:indexPath.row];
    if(currentAwsData)
    {        
        // Set the correct text to the UILabel
        NSString *currentValueText;
        switch(indexPath.row)
        {
            case DS_AIRPRESSURE_INDEX:
                currentValueText = [NSString stringWithFormat:@"%.3f hPa",currentAwsData.airPressure];
                break;
            case DS_HUMIDITY_INDEX:
                currentValueText = [NSString stringWithFormat:@"%d ",currentAwsData.humidity];
                currentValueText = [currentValueText stringByAppendingString:@"%"];
                break;
            case DS_RAINRATE_INDEX:
                currentValueText= [NSString stringWithFormat:@"%d mm",currentAwsData.rainRate];
                break;
            case DS_TEMP_INDEX:
                currentValueText= [NSString stringWithFormat:@"%.1f C",currentAwsData.temperature];
                break;
            case DS_WINDDIR_INDEX:
                imageCell.title.text= [tableData objectAtIndex:DS_WINDDIR_INDEX];
                [UIImageView beginAnimations:nil context:nil];
                [UIImageView setAnimationDuration:2];
                [UIImageView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                //rotation is in RAD!
                imageCell.arrow.transform = CGAffineTransformMakeRotation(
                (currentAwsData.windDirection * M_PI/180 ));
                [UIImageView commitAnimations];
                return  imageCell;
                break;
            case DS_WINDSPEED_INDEX:
                currentValueText= [NSString stringWithFormat:@"%.1f m/s",currentAwsData.windSpeed];
                break;
        }
        cell.Value.text = currentValueText;
    }
    
    return cell;
}

- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
   [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // find the selected cell
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    selectedTableIndex = indexPath.row;
    // perform the segue
    [self performSegueWithIdentifier:@"GraphSegue" sender:cell];
}

//called just before performing the segue
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    GraphViewController *graph = (GraphViewController *) segue.destinationViewController;
    //preload the data in the background
    [graph setDataStreamIndex:selectedTableIndex];
}


- (void)operationFailed:(AFHTTPRequestOperation *)operation withError:(NSError *)error
{
    [self.refreshControl endRefreshing];
}

- (void)operationCompleted:(AFHTTPRequestOperation *)operation byResponse:(id)responseObject
{
    // Parse response
    NSData *response = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData: response options: NSJSONReadingMutableContainers error: nil];

    // Array of datastreams
    NSArray *datastreams = [json objectForKey:@"datastreams"];
    
    // Put datastream in NSMutableArray
    NSMutableArray* currentValues = [[NSMutableArray alloc] init];
    for(NSDictionary *datastream in datastreams)
    {
        NSObject *value = [datastream objectForKey:@"current_value"];
        [currentValues addObject:value];
    }
    // Create new Object with the current AWS data
    currentAwsData = [[CurrentAwsData alloc] initWithParams:currentValues[0] :currentValues[1] :currentValues[2] :currentValues[3] :currentValues[4] :currentValues[5]];
    
    [self.tableView reloadData];
    [self.refreshControl endRefreshing];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
